package cn.itsource.controller;

import cn.itsource.dto.CodeDto;
import cn.itsource.exception.MyException;
import cn.itsource.result.JSONResult;
import cn.itsource.util.MyTools;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@RequestMapping("verifycode")
public class VerifyCodeController {
    @Autowired
    private RedisTemplate redisTemplate;
    @GetMapping("/imageCode/{imageCodeValue}")
    public JSONResult createImageCode(@PathVariable(value = "imageCodeValue") String imageCodeValue){
        //生成验证码
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 35, 4);
        //设置验证码类型
        specCaptcha.setCharType(Captcha.TYPE_ONLY_NUMBER);
        String code = specCaptcha.text();
        //存redis
        redisTemplate.opsForValue().set(imageCodeValue,code,1, TimeUnit.MINUTES);
        //返回图片base64
        return JSONResult.success(specCaptcha.toBase64());
    }
    @PostMapping("/sendSmsCode")
    public JSONResult sendSmsCode(@RequestBody CodeDto dto){
        //判断手机号是否在redis里面
        String phone= (String) redisTemplate.opsForValue().get(dto.getMobile());
        if(StringUtils.hasLength(phone)){
            throw  new MyException("手机号已经注册");
        }
        //根据uuid获取验证码和验证码对比
        String code = (String) redisTemplate.opsForValue().get(dto.getImageCodeKey());
        if(!StringUtils.hasLength(dto.getImageCode())){
            throw new MyException("请输入验证码");
        }
        if(!code.equals(dto.getImageCode())){
            throw  new MyException("验证码不正确");
        }
        //生成验证码
        String randomNum = MyTools.getRandomNum(6);
        //打印验证码
        log.info("验证码:{}",randomNum);
        //存储redis
        redisTemplate.opsForValue().set(dto.getMobile(),randomNum,2,TimeUnit.MINUTES);
        return JSONResult.success();
    }
}
